package com.own.stu.apm.agent.core.boot;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.net.URL;

@Slf4j
public class AgentPackagePath {
    private static File AGENT_PACKAGE_PATH;

    public static File getPath() {
        if (AGENT_PACKAGE_PATH == null) {
            AGENT_PACKAGE_PATH = findPath();
        }
        return AGENT_PACKAGE_PATH;
    }

    /**
     *  apm-agent.jar所在目录的file对象
     * @return
     */
    private static File findPath() {

        // com/roadjava/skywalking/demo/apm/agent/core/boot/AgentPackagePath.class
        String classResourcePath = AgentPackagePath.class.getName().replaceAll("\\.", "/") + ".class";

        URL resource=ClassLoader.getSystemClassLoader().getResource(classResourcePath);
        if(resource != null) {
            String urlString = resource.toString();
            //log.info("The beacon class location is {}.", urlString);
            boolean isInJar = urlString.indexOf('!') > -1;
            if (isInJar) {
                urlString = StringUtils.substringBetween(urlString, "file:", "!");
                File agentJarFile = null;
                try {
                    agentJarFile = new File(urlString);
                } catch (Exception e) {
                    log.error("can not locate agent jar file by url:{}", urlString, e);
                }
                if (agentJarFile.exists()) {
                    return agentJarFile.getParentFile();
                }
            }
        }
        log.error("can not locate agent jar file.");
        throw new RuntimeException("can not locate agent jar file.");
    }
}
